package com.hermit.qmst.service;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.SysMsgInterstitial;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.FileUtils;
import com.hermit.qmst.tools.Log;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class SysMessageIntentService extends IntentService {

    public SysMessageIntentService(){
        super("SysMessageIntentService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        request();
    }

    private void request(){
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.getCache().clear();
        String url = Common.submitQueryTextPath();
        StringRequest request = new StringRequest(Request.Method.POST,url,new Response.Listener<String>(){

            @Override
            public void onResponse(String s) {
                Log.i("SystemActivity", s, true);
                if (s != null && s.length() > 0){

                    try{

                        JSONObject jsonObject = new JSONObject(s);

                        if (jsonObject.getString("status").equals("1")){
                            JSONArray dataArr = jsonObject.getJSONArray("data");
                            JSONObject item = dataArr.getJSONObject(0);
                            String content = item.getString("content");

                            FileUtils fileUtils = new FileUtils();
                            String old = fileUtils.readTxt(Common.getDialImageDirPath(), Common.mSysMessageTxtFileName);
                            if (old == null || !old.equals(content)){
                                //弹出到消息中心
                                showInterstitialNotification(content,1);
                                fileUtils.saveTxtFile(Common.getDialImageDirPath(),Common.mSysMessageTxtFileName,content);
                            }

                        }
                    }catch (Exception e){

                    }
                }
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }){
            @Override
            public byte[] getBody() {
                String requestParam =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>systeminfo</type><uid>"+Common.mInfoId+"</uid><phone>"+ Common.myPhone +"</phone></data>";
                byte[] b = null;
                try {
                    b = requestParam.getBytes("utf-8");
                }catch (Exception e){
                    b = requestParam.getBytes();
                }
                return b;
            }
        };

        requestQueue.add(request);


    }


    @SuppressLint("InlinedApi")
    private void showInterstitialNotification(String msg,int id){
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, SysMsgInterstitial.class);
        intent.putExtra("SYS_MSG", msg);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notif = new Notification(R.drawable.ic_launcher, getString(R.string.app_name),
                System.currentTimeMillis());
        notif.setLatestEventInfo(SysMessageIntentService.this, getString(R.string.app_name), msg, contentIntent);
        notif.defaults = Notification.DEFAULT_ALL;
        nm.notify(id, notif);
    }


}
